<template>
  <div class="setting">
    <!-- card卡片部分 -->
    <el-card class="box-card">
      <!-- tabs标签页 -->
      <el-tabs v-model="activeName">
        <el-tab-pane label="角色管理" name="first">
          <!-- 角色管理部分 -->
          <!-- 按钮 -->
          <el-button
            type="primary"
            size="mini"
            icon="el-icon-search"
            @click="dialogFormVisible = true"
          >新增角色</el-button>

          <!-- table -->
          <el-table
            :data="tableData"
            border
            style="width: 100%"
            :default-sort="{ prop: 'date', order: 'descending' }"
          >
            <el-table-column type="index" label="序号" width="90" />
            <el-table-column prop="name" label="角色名" width="180" sortable />
            <el-table-column prop="description" label="描述" sortable />
            <el-table-column fixed="right" label="操作">
              <!-- 通过slot自定义结构,如果要获取这一行的数据,可以通过.row属性 -->
              <!-- #default="{ row }" -->
              <template #default="{ row }">
                <el-button
                  type="text"
                  size="small"
                  @click="handleClick(row)"
                >分配权限</el-button>
                <el-button
                  type="text"
                  size="small"
                  @click="enterEdit(row)"
                >修改</el-button>
                <el-button
                  type="text"
                  size="small"
                  @click="deleteRole(row)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <!-- current-page：当前页数
              page-sizes：每页显示几条的选项设置
              page-size：每页显示几条
              @size-change:pageSize 改变时会触发
              @current-change:current-page改变时触发
           -->
          <el-pagination
            :current-page="page"
            :page-sizes="[1, 2, 3, 5]"
            :page-size="pagesize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-tab-pane>
        <el-tab-pane label="公司信息" name="second">
          <!-- 公司信息部分 -->
          <com-info />
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 弹框 -->
    <!-- <set-dialog :visible="isShow" @update:visible="isShow = $event" /> -->
    <el-dialog
      :title="title"
      :visible.sync="dialogFormVisible"
      @closed="clearHandler"
    >
      <el-form ref="form" :model="form" :rules="rules">
        <el-form-item
          label="角色名称"
          :label-width="formLabelWidth"
          prop="name"
        >
          <el-input v-model="form.name" autocomplete="off" />
        </el-form-item>
        <el-form-item
          label="角色描述"
          :label-width="formLabelWidth"
          prop="description"
        >
          <el-input v-model="form.description" autocomplete="off" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="clearHandler">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getRoles,
  addRole,
  getRoleById,
  editRoleById,
  deleteRole
} from '@/api/setting'
import comInfo from './components/comInfo.vue'
// import setDialog from './components/setDialog.vue'
export default {
  name: 'Setting',
  components: { comInfo },
  data() {
    return {
      // s是否显示弹框
      // isShow: false,
      dialogFormVisible: false,
      activeName: 'first',
      // 角色管理数据数组
      tableData: [],
      // 总页数
      total: 1,
      page: 1, // 页码
      pagesize: 2, // 每页显示条数
      // 表单数据
      form: {
        name: '',
        description: ''
        // index: 1
      },
      formLabelWidth: '100px',
      rules: {
        name: [{ required: true, message: '不能为空', trigger: 'blur' }],
        description: [{ required: true, message: '不能为空', trigger: 'blur' }]
      }
    }
  },

  computed: {
    title() {
      return this.form.id ? '编辑角色' : '新增角色'
    }
  },
  created() {
    // 页面一开始就要加载数据
    this.getDate()
  },

  methods: {
    // 封装获取数据的函数
    async getDate() {
      const res = await getRoles({ page: this.page, pagesize: this.pagesize })
      // console.log(res)
      this.tableData = res.rows
      // 保存总条数
      this.total = res.total
    },
    // 每页多少条改变时触发
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`)
      this.pagesize = val
      // 一般会重新返回第一页
      this.page = 1
      this.getDate()
    },
    // 当前页改变时触发（页码改变时）
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`)
      this.page = val
      this.getDate()
    },

    // 新增角色
    submitForm() {
      // validate:对整个表单进行验证
      this.$refs.form.validate(async(valid) => {
        if (valid) {
          if (this.form.id) {
            // 有id就是编辑
            await editRoleById(this.form)
          } else {
            // 没有id就是新增
            await addRole(this.form)
          }
          this.$message.success(`${this.title}成功`)
          this.getDate()
          this.dialogFormVisible = false
        } else {
          console.log('数据格式有误，请重新检查')
          return false
        }
      })
    },

    // 编辑角色
    async enterEdit(row) {
      // console.log(row)
      const res = await getRoleById(row.id)
      this.form = { ...res }
      this.dialogFormVisible = true
    },

    // 清空表单
    clearHandler() {
      this.form = {
        name: '',
        description: ''
      }
      this.dialogFormVisible = false
    },

    // 删除事件
    async deleteRole(row) {
      this.$confirm('是否要删除该角色？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          if (this.page != 1 && this.tableData.length == 1) {
            this.page--
          }
          await deleteRole(row.id)
          this.getDate()
          this.$message({
            type: 'success',
            message: '删除角色成功!'
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    }
  }
}
</script>

<style lang="scss">
.setting {
  .box-card.el-card.is-always-shadow {
    box-shadow: 0 2px 12px 0 #f5cace;
    .el-button {
      margin-bottom: 10px;
    }
    .el-button--primary {
      background: #f5cacd;
      border: transparent;
    }
    .el-tabs__item.is-active {
      color: #f5cacd;
    }
    .el-tabs__active-bar {
      background-color: #f5cacd;
    }
  }
  .el-form-item__content {
    width: 600px;
  }
  .el-pagination {
    margin-top: 20px;
    text-align: right;
  }
  .el-input {
    width: 80%;
  }
}
</style>
